<template>
  <canvas ref="barChart" width="600" height="400"></canvas>
</template>
<script>export default {
  props: { data: { type: Array, required: true } },
  mounted() {
    this.drawBarChart()
  },
  methods: {
    drawBarChart() {
      const canvas = this.$refs.barChart
      const ctx = canvas.getContext('2d')
      const chartHeight = canvas.height - 50
      const chartWidth = canvas.width - 100
      const maxValue = Math.max(...this.data.map(item => item.value))
      const barWidth = chartWidth / this.data.length * 0.8
      const gap = chartWidth / this.data.length * 0.2
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      ctx.beginPath()
      ctx.moveTo(50, 0)
      ctx.lineTo(50, chartHeight)
      ctx.lineTo(canvas.width, chartHeight)
      ctx.fillText('金额(元)', 30, 20) // 填写具体单位
      ctx.strokeStyle = '#000'
      ctx.stroke()
      ctx.textAlign = 'center'
      ctx.fillStyle = '#000'
      ctx.fillText('日期', canvas.width - 20, canvas.height - 30)
      this.data.forEach((item, index) => {
        const x = 50 + gap / 2 + index * (barWidth + gap)
        const height = (item.value / maxValue) * (chartHeight - 50)
        ctx.fillStyle = item.color
        ctx.fillRect(x, chartHeight - height, barWidth, height)
        ctx.fillStyle = '#000'
        ctx.textAlign = 'center'
        ctx.fillText(item.value, x + barWidth / 2, chartHeight - height - 5)
        ctx.fillText(item.label, x + barWidth / 2, chartHeight + 20)
      })
    }
  },
  watch: {
    data: {
      handler() {
        this.drawBarChart()
      }, deep: true
    }
  }
}</script>
